﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitOperations
{
    /* Problem description
     * 
     * Given a byte, reverse the bits in the byte
     *      
     */

    class ReverseByteProblem
    {
        /* Algorithm
         * 
         * Use a new byte (result) to store the new byte value
         * the new byte will shift from Right to Left
         * the old byte will shift from Left to Right
         * this way, the lower bit of the old byte will become the higher bit of the new byte
         * 
         * the tricky part is, in the new byte, after it is left shifted, it needs to do an "OR" with the last bit of the old byte
         * 
         */ 

        public byte ReverseBit(byte val)
        {
            byte result = 0;

            int counter = 8;
            for(int i=0; i<counter; i++)
            {
                result <<= 1;
                result |= (byte)(val & 1);
                val = (byte)(val >> 1);
            }

            return result;
        }

        static void Main(string[] args)
        {
            byte value = 43;
            Console.WriteLine("original number: " + Convert.ToString(value, 2));

            ReverseByteProblem rb = new ReverseByteProblem();

            byte newbyte = rb.ReverseBit(value);
            Console.WriteLine("new number: " + Convert.ToString(newbyte, 2));

            Console.WriteLine("Press any key to finish...");
            Console.ReadKey();
        }
    }
}